<template>
	<view class="cart-container" v-if="cartList.length !== 0">
		<!-- 选择收货地址的盒子 -->
		<view class="address-choose-box" v-if="JSON.stringify(userAddress) === '{}'">
			<button type="primary" size="mini" class="btnChooseAddress" @click="clickConsigneeBtn">请选择收货地址+</button>
		</view>

		<view class="goods-title" v-else @click="clickGoodsTitle">
			<view class="goods-consignee-info">
				<view class="user-name">收货人：{{userAddress.userName}}</view>
				<view class="user-phone">电话：<text>{{userAddress.telNumber}}</text>
					<uni-icons type="arrowright" size="16"></uni-icons>
				</view>
			</view>
			<view class="user-address">收货地址：{{consignee}}</view>
		</view>

		<image src="@/static/cart_border@2x.png" style="width: 100%; height: 5px;"></image>
		<view class="goods-box">
			<view class="goods-box-header">
				<uni-icons type="shop" size="18"></uni-icons>
				<!-- 描述文本 -->
				<text class="cart-title-text">购物车</text>
			</view>
			<view class="goods-box-main">
				<uni-swipe-action>
					<block v-for="item in cartList" :key="item.goods_id">
						<uni-swipe-action-item :right-options="options" @click="swipeActionClickHandler(item)">
							<my-goodsList :goods="item" :showRadio="true" @radio-change="radioChangeHandler"
								isShowNumberBox @changeNumberBox="changeNumberBoxHandler"></my-goodsList>
						</uni-swipe-action-item>
					</block>
				</uni-swipe-action>
			</view>
		</view>

		<!-- 最外层的容器 -->
		<view class="my-settle-container">
			<!-- 全选区域 -->
			<label class="radio">
				<radio color="#C00000" :checked="isFullCheck" @click="isAllChecked" /><text>全选</text>
			</label>
			<!-- 合计区域 -->
			<view class="amount-box">
				合计:<text class="amount">￥{{checkTotal}}</text>
			</view>
			<!-- 结算按钮 -->
			<view class="btn-settle" @click="settlement">结算({{goodsTotal}})</view>
		</view>
	</view>
	<view class="empty-cart" v-else>
		<image src="/static/cart_empty@2x.png" class="empty-img"></image>
		<text class="tip-text">空空如也~</text>
	</view>
</template>

<script>
	import {
		mapGetters,
		mapState,
		mapMutations
	} from 'vuex'
	import badgeMix from '@/mixins/tabbar-badge.js'
	export default {
		mixins: [badgeMix],
		data() {
			return {
				options: [{
					text: '删除', // 显示的文本内容
					style: {
						backgroundColor: '#C00000' // 按钮的背景颜色
					}
				}],
				// 倒计时的秒数
				seconds: 3,
				// 
				time: null
			};
		},
		computed: {
			...mapState('cart', ['cartList']),
			...mapState('m_user', ['userAddress', 'token']),
			...mapGetters('cart', ['goodsTotal', 'cartTotal', 'checkTotal']),
			...mapGetters('m_user', ['addstr']),
			consignee() {
				return this.userAddress.provinceName + this.userAddress.cityName + this.userAddress.countyName +
					this.userAddress
					.detailInfo
			},
			isFullCheck() {
				return this.goodsTotal === this.cartTotal
			}
		},
		methods: {
			...mapMutations('cart', ['updateGoodsRadio', 'updateNumberBox', 'removeGoodsById', 'updateAllGoodsState']),
			...mapMutations('m_user', ['setUserAddress', 'updateRedirectInfo']),
			radioChangeHandler(e) {
				this.updateGoodsRadio(e)
			},
			changeNumberBoxHandler(e) {
				this.updateNumberBox(e)
			},
			swipeActionClickHandler(goods) {
				this.removeGoodsById(goods)
			},
			// 点击收货地址
			async clickConsigneeBtn() {
				const that = this
				// 用户发起授权请求
				const [err, succ] = await uni.authorize({
					scope: 'scope.address'
				})

				// 授权成功
				if (succ && succ.errMsg === 'authorize:ok') {
					const [errAddress, succAddress] = await uni.chooseAddress().catch(err => err)
					if (succAddress && succAddress.errMsg === 'chooseAddress:ok') {
						this.setUserAddress(succAddress)
					}

					if (errAddress && errAddress.errMsg === 'chooseAddress:fail cancel') {
						uni.$showMsg('获取用户收货地址失败')
					}
					// 授权失败 || 没有授权
				} else {
					const [errShowModal, succShowModal] = await uni.showModal({
						title: '温馨提示',
						content: '您已拒绝授权，是否去设置打开？',
						confirmText: "确认",
						cancelText: "取消",
					})

					if (succShowModal && succShowModal.confirm) {
						uni.openSetting()
					}

					if (succShowModal && succShowModal.cancel) {
						uni.$showMsg('取消授权')
					}
				}
			},
			clickGoodsTitle() {
				this.clickConsigneeBtn()
			},
			// 点击全选
			isAllChecked() {
				this.updateAllGoodsState(!this.isFullCheck)
			},
			// 结算
			async settlement() {
				// 是否有选择收货地址
				if (!this.addstr) return uni.$showMsg('请选择收货地址')

				// 是否有选择商品
				if (!this.goodsTotal) return uni.$showMsg('请选择商品')

				// 判断是否登录
				if (!this.token) {
					this.seconds = 3

					this.showTips(this.seconds)

					this.time = setInterval(() => {
						this.seconds--

						if (this.seconds < 0) {
							clearInterval(this.time)
							uni.switchTab({
								url: '/pages/my/my'
							})
							this.updateRedirectInfo({
								openType: 'switchTab',
								from: '/pages/cart/cart'
							})
							return
						}

						this.showTips(this.seconds)

					}, 1000)
				} else {
					const params = {
						// 订单总价格
						order_price: 0.01,
						// 收货地址
						consignee_addr: this.addstr,
						// 商品信息
						goods: this.cartList.map((x) => {
							return {
								goods_id: x.goods_id,
								goods_number: x.goods_count,
								goods_price: x.goods_price
							}
						})
					}

					const {
						data: res
					} = await uni.$http.post(
						'/api/public/v1/my/orders/create', params)

					if (res.meta.status !== 200) return uni.$showMsg('创建订单成功失败')
					// 订单编号
					const {
						order_number: orderNumber
					} = res.message

					const {
						data: res2
					} = await uni.$http.post('/api/public/v1/my/orders/req_unifiedorder', {
						order_number: orderNumber
					})

					if (res2.meta.status !== 200) return uni.$showMsg('预付订单生成失败')
					
					const payInfo = res2.message.pay
					uni.requestPayment({
						timeStamp: payInfo.timeStamp,
						nonceStr: payInfo.nonceStr,
						package: payInfo.package,
						signType: payInfo.signType,
						paySign: payInfo.paySign,
						success: (data) => {
							console.log(data)
						},
						fail: (data) => {
							console.log(data, 'fail')
						}
					})
					// if(err) return uni.$showMsg('订单未支付')
					// 查询订单
					// const res3 = await uni.$http.post('/api/public/v1/my/orders/chkOrder', orderNumber)
					// console.log(res3)
				}
			},
			showTips(n) {
				uni.showToast({
					icon: 'none',
					title: `请登录后再结算！${n} 秒后自动跳转到登录页`,
					mask: true
				})
			}
		}
	}
</script>

<style lang="scss">
	.goods-box-header {
		height: 40px;
		display: flex;
		align-items: center;
		font-size: 14px;
		padding-left: 5px;
		border-bottom: 1px solid #efefef;

		.cart-title-text {
			margin-left: 10px;
		}
	}

	.goods-title {
		padding: 0 5px 10px;
		font-size: 14px;

		.goods-consignee-info {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin: 20px 0 10px 0;
		}
	}

	.address-choose-box {
		height: 90px;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.my-settle-container {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		height: 50px;
		// 将背景色从 cyan 改为 white
		background-color: white;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding-left: 5px;
		font-size: 14px;

		.radio {
			display: flex;
			align-items: center;
		}

		.amount {
			color: #c00000;
		}

		.btn-settle {
			height: 50px;
			min-width: 100px;
			background-color: #c00000;
			color: white;
			line-height: 50px;
			text-align: center;
			padding: 0 10px;
		}
	}

	.empty-cart {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding-top: 150px;

		.empty-img {
			width: 90px;
			height: 90px;
		}

		.tip-text {
			font-size: 12px;
			color: gray;
			margin-top: 15px;
		}
	}
</style>
